<template>
  <div
    class="window"
    :class="{
      focused: window.isFocused,
      maximized: window.isMaximized,
      minimized: window.isMinimized,
      'maximizing': isMaximizing,
      'minimizing': isMinimizing,
      'restoring': isRestoring
    }"
    :style="windowStyle"
    @mousedown="handleFocus"
  >
    <!-- 窗口控制按钮 - 悬浮设计 -->
    <div
      class="window-titlebar"
      @mousedown="handleDragStart"
      @dblclick="handleDoubleClick"
    >
      <div class="window-controls">
        <div class="control-btn close" @click.stop="handleClose"></div>
        <div class="control-btn minimize" @click.stop="handleMinimize"></div>
        <div class="control-btn maximize" @click.stop="handleMaximize"></div>
      </div>
    </div>

    <!-- 窗口内容 -->
    <div class="window-content">
      <component
        :is="appComponent"
        v-if="appComponent"
      />
      <div v-else class="placeholder-content">
        <div class="app-icon">{{ appIcon }}</div>
        <h2>{{ window.title }}</h2>
        <p>应用内容区域</p>
      </div>
    </div>

    <!-- 调整大小手柄 -->
    <div
      v-if="!window.isMaximized"
      class="resize-handle resize-right"
      @mousedown.stop="handleResizeStart('right', $event)"
    ></div>
    <div
      v-if="!window.isMaximized"
      class="resize-handle resize-bottom"
      @mousedown.stop="handleResizeStart('bottom', $event)"
    ></div>
    <div
      v-if="!window.isMaximized"
      class="resize-handle resize-corner"
      @mousedown.stop="handleResizeStart('corner', $event)"
    ></div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useDesktopStore, type WindowState } from '../../stores/desktop'

// 导入应用配置和组件
import { loadAppsSync } from '@/lib/appLoader'

// 自动加载所有应用并创建组件映射
const loadedApps = loadAppsSync()
const componentMap = loadedApps.reduce((map, app) => {
  map[app.id.charAt(0).toUpperCase() + app.id.slice(1)] = app.component
  return map
}, {} as Record<string, any>)

const props = defineProps<{
  window: WindowState
}>()

const desktopStore = useDesktopStore()
const isDragging = ref(false)
const isResizing = ref(false)
const isMaximizing = ref(false)
const isMinimizing = ref(false)
const isRestoring = ref(false)
const resizeDirection = ref<string>('')
const dragStart = ref({ x: 0, y: 0, windowX: 0, windowY: 0 })
const resizeStart = ref({ x: 0, y: 0, width: 0, height: 0 })
const wasMinimized = ref(false)

const app = computed(() =>
  desktopStore.apps.find(a => a.id === props.window.appId)
)

const appIcon = computed(() => app.value?.icon || '📦')

const appComponent = computed(() => {
  const componentName = app.value?.component
  if (!componentName) return null

  // 从动态加载的组件映射中获取组件
  return componentMap[componentName] || null
})

const windowStyle = computed(() => {
  if (props.window.isMaximized) {
    return {
      left: '0px',
      top: '32px',
      width: '100vw',
      height: 'calc(100vh - 32px - 90px)',
      zIndex: props.window.zIndex,
    }
  }

  return {
    left: `${props.window.x}px`,
    top: `${props.window.y}px`,
    width: `${props.window.width}px`,
    height: `${props.window.height}px`,
    zIndex: props.window.zIndex,
  }
})

function handleFocus() {
  // 总是调用 focusApp 以确保窗口被带到最前面
  desktopStore.focusApp(props.window.appId)
}

function handleClose() {
  desktopStore.closeApp(props.window.appId)
}

function handleMinimize() {
  isMinimizing.value = true
  setTimeout(() => {
    desktopStore.minimizeApp(props.window.appId)
    isMinimizing.value = false
  }, 350)
}

function handleMaximize() {
  isMaximizing.value = true
  setTimeout(() => {
    desktopStore.toggleMaximize(props.window.id)
    setTimeout(() => {
      isMaximizing.value = false
    }, 50)
  }, 50)
}

function handleDoubleClick() {
  handleMaximize()
}

function handleDragStart(e: MouseEvent) {
  if (props.window.isMaximized) return

  isDragging.value = true
  dragStart.value = {
    x: e.clientX,
    y: e.clientY,
    windowX: props.window.x,
    windowY: props.window.y,
  }

  document.addEventListener('mousemove', handleDragMove)
  document.addEventListener('mouseup', handleDragEnd)

  e.preventDefault()
}

function handleDragMove(e: MouseEvent) {
  if (!isDragging.value) return

  const deltaX = e.clientX - dragStart.value.x
  const deltaY = e.clientY - dragStart.value.y

  let newX = dragStart.value.windowX + deltaX
  let newY = dragStart.value.windowY + deltaY

  // 限制在屏幕内
  newY = Math.max(32, Math.min(newY, window.innerHeight - 100))
  newX = Math.max(-props.window.width + 100, Math.min(newX, window.innerWidth - 100))

  desktopStore.updateWindowPosition(props.window.id, newX, newY)
}

function handleDragEnd() {
  isDragging.value = false
  document.removeEventListener('mousemove', handleDragMove)
  document.removeEventListener('mouseup', handleDragEnd)
}

function handleResizeStart(direction: string, e: MouseEvent) {
  isResizing.value = true
  resizeDirection.value = direction
  resizeStart.value = {
    x: e.clientX,
    y: e.clientY,
    width: props.window.width,
    height: props.window.height,
  }

  document.addEventListener('mousemove', handleResizeMove)
  document.addEventListener('mouseup', handleResizeEnd)

  e.preventDefault()
}

function handleResizeMove(e: MouseEvent) {
  if (!isResizing.value) return

  const deltaX = e.clientX - resizeStart.value.x
  const deltaY = e.clientY - resizeStart.value.y

  let newWidth = resizeStart.value.width
  let newHeight = resizeStart.value.height

  // 计算器使用更小的最小尺寸
  const minWidth = props.window.appId === 'calculator' ? 260 : 400
  const minHeight = props.window.appId === 'calculator' ? 350 : 300

  if (resizeDirection.value === 'right' || resizeDirection.value === 'corner') {
    newWidth = Math.max(minWidth, resizeStart.value.width + deltaX)
  }

  if (resizeDirection.value === 'bottom' || resizeDirection.value === 'corner') {
    newHeight = Math.max(minHeight, resizeStart.value.height + deltaY)
  }

  desktopStore.updateWindowSize(props.window.id, newWidth, newHeight)
}

function handleResizeEnd() {
  isResizing.value = false
  resizeDirection.value = ''
  document.removeEventListener('mousemove', handleResizeMove)
  document.removeEventListener('mouseup', handleResizeEnd)
}

// 监听最小化状态变化，处理恢复动画
watch(() => props.window.isMinimized, (newVal, oldVal) => {
  if (oldVal === true && newVal === false) {
    // 从最小化恢复
    isRestoring.value = true
    setTimeout(() => {
      isRestoring.value = false
    }, 400)
  }
})
</script>

<style scoped>
.window {
  position: absolute;
  background: transparent;
  border-radius: 12px;
  box-shadow:
    0 20px 60px rgba(0, 0, 0, 0.3),
    0 0 0 0.5px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  transition: 
    box-shadow 0.2s ease,
    transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);
  transform-origin: center center;
}

/* 深色模式窗口阴影 */
html.dark-mode .window {
  box-shadow:
    0 20px 60px rgba(0, 0, 0, 0.6),
    0 0 0 0.5px rgba(255, 255, 255, 0.1);
}

.window.focused {
  box-shadow:
    0 25px 70px rgba(0, 0, 0, 0.4),
    0 0 0 0.5px rgba(0, 0, 0, 0.3);
}

html.dark-mode .window.focused {
  box-shadow:
    0 25px 70px rgba(0, 0, 0, 0.7),
    0 0 0 0.5px rgba(255, 255, 255, 0.15);
}

/* 最大化状态 */
.window.maximized {
  border-radius: 0;
  transition: 
    all 0.4s cubic-bezier(0.4, 0, 0.2, 1),
    border-radius 0.35s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 正在最大化/恢复的动画 */
.window.maximizing {
  transition: 
    all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1),
    border-radius 0.35s cubic-bezier(0.4, 0, 0.2, 1) !important;
}

/* 最小化动画 */
.window.minimizing {
  animation: minimizeWindow 0.35s cubic-bezier(0.4, 0, 1, 1) forwards;
  pointer-events: none;
}

@keyframes minimizeWindow {
  0% {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
  100% {
    opacity: 0;
    transform: scale(0.3) translateY(100vh);
  }
}

/* 最小化状态 - 隐藏但保持渲染以保活 */
.window.minimized {
  visibility: hidden;
  opacity: 0;
  pointer-events: none;
  transform: scale(0.3) translateY(100vh);
}

/* 从最小化恢复时的动画 */
.window.restoring {
  animation: restoreWindow 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
}

@keyframes restoreWindow {
  from {
    visibility: visible;
    opacity: 0;
    transform: scale(0.3) translateY(100vh);
  }
  to {
    visibility: visible;
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.window-titlebar {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 52px;
  display: flex;
  align-items: center;
  padding: 0 12px;
  cursor: move;
  user-select: none;
  z-index: 10;
  pointer-events: none;
}

.window-titlebar > * {
  pointer-events: all;
}

.window-controls {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 8px 10px;
  border-radius: 8px;
  background: transparent;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 鼠标悬停在控制按钮区域时的背景效果 */
.window-controls:hover {
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(20px) saturate(180%);
  -webkit-backdrop-filter: blur(20px) saturate(180%);
  box-shadow: 
    0 2px 10px rgba(0, 0, 0, 0.08),
    0 0 0 0.5px rgba(255, 255, 255, 0.2) inset;
  transform: scale(1.02);
}

/* 非聚焦窗口的控制按钮悬停效果稍弱 */
.window:not(.focused) .window-controls:hover {
  background: rgba(255, 255, 255, 0.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

/* 深色模式下的控制按钮背景 */
html.dark-mode .window-controls:hover {
  background: rgba(255, 255, 255, 0.1);
  box-shadow: 
    0 2px 12px rgba(0, 0, 0, 0.2),
    0 0 0 0.5px rgba(255, 255, 255, 0.15) inset;
}

html.dark-mode .window:not(.focused) .window-controls:hover {
  background: rgba(255, 255, 255, 0.06);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.control-btn {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.34, 1.56, 0.64, 1);
  position: relative;
}

.control-btn:hover {
  transform: scale(1.15);
}

.control-btn:active {
  transform: scale(0.95);
}

.control-btn::after {
  content: '';
  position: absolute;
  inset: 0;
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.control-btn:hover::after {
  opacity: 1;
}

.control-btn.close {
  background: #ff5f56;
}

.control-btn.close:hover::after {
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12"><path d="M 3 3 L 9 9 M 9 3 L 3 9" stroke="%23000" stroke-width="1.5" stroke-linecap="round"/></svg>') center/8px no-repeat;
}

.control-btn.minimize {
  background: #ffbd2e;
}

.control-btn.minimize:hover::after {
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12"><path d="M 3 6 L 9 6" stroke="%23000" stroke-width="1.5" stroke-linecap="round"/></svg>') center/8px no-repeat;
}

.control-btn.maximize {
  background: #27c93f;
}

.control-btn.maximize:hover::after {
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12"><path d="M 3 4 L 3 9 L 9 9 L 9 4 M 5 4 L 5 3 L 9 3" stroke="%23000" stroke-width="1" fill="none"/></svg>') center/10px no-repeat;
}

.window:not(.focused) .control-btn {
  background: rgba(0, 0, 0, 0.15);
}

.window-content {
  flex: 1;
  overflow: auto;
  background: transparent;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.window.maximizing .window-content {
  transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
}

/* 为某些应用添加顶部内边距，避免内容被控制按钮遮挡 */
.window-content > * {
  position: relative;
  height: 100%;
}

.placeholder-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  color: #86868b;
  background: white;
}

html.dark-mode .placeholder-content {
  color: #98989d;
  background: #2c2c2e;
}

.placeholder-content .app-icon {
  font-size: 64px;
  filter: drop-shadow(0 4px 12px rgba(0, 0, 0, 0.1));
}

.placeholder-content h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
}

html.dark-mode .placeholder-content h2 {
  color: #f5f5f7;
}

.placeholder-content p {
  font-size: 14px;
}

/* 调整大小手柄 */
.resize-handle {
  position: absolute;
  background: transparent;
}

.resize-handle.resize-right {
  right: 0;
  top: 0;
  bottom: 0;
  width: 8px;
  cursor: ew-resize;
}

.resize-handle.resize-bottom {
  left: 0;
  right: 0;
  bottom: 0;
  height: 8px;
  cursor: ns-resize;
}

.resize-handle.resize-corner {
  right: 0;
  bottom: 0;
  width: 16px;
  height: 16px;
  cursor: nwse-resize;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .window {
    border-radius: 8px;
  }

  .window-titlebar {
    height: 36px;
  }

  .control-btn {
    width: 10px;
    height: 10px;
  }
}
</style>

